package com.ruoyi.web.pgci.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.web.pgci.service.ReadExcelService;
import com.ruoyi.web.pgci.vo.ReadTrainingMatrixVo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author yyq
 * @create 2023-11-13
 * @description Training Matrix Listener
 */
@Slf4j
public class TrainingMatrixListener implements ReadListener<ReadTrainingMatrixVo> {


    private ReadExcelService readExcelService;

    public TrainingMatrixListener(ReadExcelService readExcelService){
        this.readExcelService = readExcelService;
    }
    /**
     * 每隔100条存储数据库
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<ReadTrainingMatrixVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ReadTrainingMatrixVo data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        Integer rowIndex = context.readRowHolder().getRowIndex();
        if (rowIndex != 4){
            return;
        }
        for (Map.Entry<Integer, ReadCellData<?>> entry : headMap.entrySet()) {
            Integer col = entry.getKey();
            ReadCellData<?> cellData = entry.getValue();
            Integer columnIndex = cellData.getColumnIndex();
            String stringValue = cellData.getStringValue();
            if (StringUtils.isBlank(stringValue)){
                continue;
            }
            readExcelService.saveTrainingPost(rowIndex,columnIndex,stringValue);
        }
        log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        readExcelService.saveTrainingMatrix(cachedDataList);
    }
}
